// Tutorial 3 - plain old javascript

// platform independent function to create an xmlHttp object
function createXmlHttp() { 
  if (typeof XMLHttpRequest != "undefined") {
    return new XMLHttpRequest();
  } else if (typeof ActiveXObject != "undefined") {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    throw new Error("AJAX not supported");
  }
}

var xmlHttp = createXmlHttp();

// function to call the server
function callServer() {
  if (xmlHttp==null) {
    alert("No AJAX!");
    return;
  }
  var hkd = this.value;
  var url = "hkd2usd.cgi";
  url = url + "?hkd=" + hkd;
  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = showAnswer;
  xmlHttp.send(null);
} 

// function that runs on response from server
function showAnswer() { 
  var e = document.getElementById("usd");
  var msg;
  if (xmlHttp.readyState==4) {
    // show the conversion
    var hkd = document.getElementById("hkd").value;
    msg = "HK$" + hkd + " = US$" + xmlHttp.responseText;
  } else {
    // still waiting for server
    msg = "calculating...";
  }
  e.innerHTML = msg;
}

// setup javascript calls unobstrusively
function setup() {
  var e = document.getElementById("hkd");
  e.onkeyup=callServer;
}

window.onload = setup;
